#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

static pthread_mutex_t mutex;
static int g_avail = 0;

static void *consumer_thread(void *arg)
{
    for (;;) {

        pthread_mutex_trylock(&mutex);
        
        printf("\n");
        printf("The cosmuer get a product!\n");
        g_avail-=1;
        printf("Current products count: %d\n\n", g_avail);
        sleep(5);

        pthread_mutex_unlock(&mutex);
    }

    return (void *)0;
}

int main(int argc, char **argv)
{
    pthread_t tid;
    int ret;

    pthread_mutex_init(&mutex, NULL);

    ret = pthread_create(&tid, NULL, consumer_thread, NULL);
    if (ret) {
        fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
        exit(-1);
    }

    for (;;) {
        pthread_mutex_trylock(&mutex);

        g_avail++;
        printf("product add, and the current count is %d\n", g_avail);
        sleep(2);

        pthread_mutex_unlock(&mutex);
    }

    exit(0);
}